package com.demo.producer;

import com.alibaba.fastjson.JSON;
import com.demo.common.Constant;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

/**
 * @author yexi
 */
public class ASyncProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer(Constant.PRODUCER_GROUP_1);
        producer.setNamesrvAddr(Constant.ROCKET_MQ_ADDRESS);
        producer.start();
        String topic = "02-async";
        String tags = "tagA";
        String msg = "RocketMQ ASync Send ";
        CountDownLatch count = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            Message message = new Message(
                    topic,
                    tags,
                    (msg + i).getBytes(StandardCharsets.UTF_8)
            );
            //发送异步消息到一个Broker。send(msg,sendCallback)为"异步发送消息"。
            producer.send(message, new SendCallback() {
                /**
                 * 异步成功回调。如果消息持久化没有问题，并且在回调的时候生产资源没有关闭，则回调onSuccess方法。
                 */
                @Override
                public void onSuccess(SendResult sendResult) {
                    count.countDown();
                    System.out.println("消息发送成功，返回消息: " + JSON.toJSONString(sendResult));
                }

                /**
                 * 如果持久化有问题或者资源已经关闭就会调用onException方法。
                 */
                @Override
                public void onException(Throwable e) {
                    count.countDown();
                    System.out.println("消息发送失败，错误信息为: " + e.getMessage());
                }
            });
        }
        //等待线程完成。若要测试异步发送消息期间关闭资源的影响可以注释。
        count.await();
        producer.shutdown();
    }
}